package cloud

import (
	"dgo/MyProj/PrjHttpUtils"
	"dgo/goutils/gohttp"
	"dgo/goutils/utils"
	"dgo/plg/plgnet"
	"dgo/sdk"
	"fmt"
	"gitee.com/ymofen/supervalue"
	"time"
)

type PlgVxApi struct {
	templmsg_cnt int32
	PlgBase
	VxUtil            *sdk.VxUtil
	templmsg_shutdown int8

	openid_code_redirect_uri   string
	openid_code_redirect_param string

	on_getopenid_action_uri   string
	on_getopenid_action_param string

	msglst    *utils.SyncCycleList
	appid     string //appid
	appsecret string //微信支付密钥，登录微信商户平台可以查看

	access_token      string
	access_token_time time.Time

	transferMap utils.GSyncMapGroup

	vxconfig_token string

	DeveloperSecret string //微信公众号开发者密码，登录微信公众号平台->基本配置可查看,https://mp.weixin.qq.com/
	mch_id          string //公众号商户号

	userlst utils.GSyncMapGroup
}

/***
{
  "id":"vx-api",
  "type":"cloud.vx.api",
  "conf":{
      "templmsg-shutdown":1,
	  "appid": "AKIDxe5LN1eoy7LL5avInS6E8rNeVn29BLFu",
	  "appsecret": "pPkqh8KRJ2XsTnJZl485xlKsAOQEbijV",
	  "baseconfig-token":"",
      "openid_code_redirect_uri":"",
      "openid_code_redirect_param":"",

      "on_getopenid_action_uri":"",
      "on_getopenid_action_param":"",

   }
}


*/

func (this *PlgVxApi) ReloadConf(conf *wrapper.SuperValue) error {

	if conf == nil {
		return nil
	}

	if this.VxUtil == nil {
		this.VxUtil = sdk.NewVxUtil()
	}

	if this.msglst == nil {
		this.msglst = utils.NewSyncCycleList()
	}

	this.VxUtil.ReloadConf(conf)

	this.templmsg_shutdown = conf.Int8ByName("templmsg-shutdown", 0)

	conf.CheckExistsStrFunc("openid_code_redirect_uri", func(strv string) {
		this.openid_code_redirect_uri = strv
	})

	conf.CheckExistsStrFunc("openid_code_redirect_param", func(strv string) {
		this.openid_code_redirect_param = strv
	})

	conf.CheckExistsStrFunc("on_getopenid_action_uri", func(strv string) {
		this.on_getopenid_action_uri = strv
	})

	conf.CheckExistsStrFunc("on_getopenid_action_param", func(strv string) {
		this.on_getopenid_action_param = strv
	})

	// 推送消息给指定用户
	gohttp.HandleFunc(fmt.Sprintf("/%s/api/templ/sendmsg", this.PlugId), this.onHttpVxTemplSendMessage)

	// 有新人关注公众号等情况微信回调接口
	gohttp.HandleFunc(fmt.Sprintf("/%s/events", this.PlugId), this.onHttpVxCallback)

	// 通过code获取openid
	gohttp.HandleFunc(fmt.Sprintf("/%s/api/getopenid/step1", this.PlugId), this.onHttpVxGetOpenIDStep1)

	gohttp.HandleFunc(fmt.Sprintf("/%s/api/getopenid/step2", this.PlugId), this.onHttpVxGetOpenIDStep2)
	gohttp.HandleFunc(fmt.Sprintf("/%s/api/getopenid/step2test", this.PlugId), this.onHttpVxGetOpenIDStep2_Test)

	return nil
}

func (this *PlgVxApi) OnHttpStatus(rec *plgnet.PlgHttpRec) (rval interface{}, errcode int, err error) {
	itype := rec.QryAsInt("type", 0)
	if itype == 99 {
		json := wrapper.NewSVObject()
		json.SetKeyValues("now", utils.NowString())
		json.SetKeyValue("templmsg-shutdown", this.templmsg_shutdown)
		json.SetKeyValue("templmsg-cnt", this.templmsg_cnt)
		if rec.QryAsInt("json", 0) == 1 {
			PrjHttpUtils.ResponseAsJSON(rec.RespW, json.AsJSONStringEx(false, true))
		} else {
			PrjHttpUtils.JSON2TableRec(rec.RespW, "", json.AsJSONString(false))
		}
	} else if itype == 98 {
		rec.ResponseSyncListNEx(this.msglst)
	} else if itype == 1 {
		json := wrapper.NewSVArray()
		//searchval := rec.QryAsString("searchval", "")
		//sn := 0
		//maxn := rec.QryAsInt("n", 100)
		//this.lst.ListRangeV2(func(key, val interface{}) bool {
		//	pojo := val.(*VrsSitePojo)
		//	ok := true
		//	if len(searchval) > 0 {
		//		ok = strings.Contains(pojo.id, searchval)
		//	}
		//	return ok
		//}, func(k0, v0, k1, v1 interface{}) bool {
		//	p0 := v0.(*VrsSitePojo)
		//	p1 := v1.(*VrsSitePojo)
		//	return p0.id < p1.id
		//}, func(key, val interface{}) bool {
		//	sn++
		//	pojo := val.(*VrsSitePojo)
		//	itm := json.AppendObject()
		//	itm.SetKeyValue("sn", sn)
		//	itm.SetKeyValue("id", pojo.id)
		//	return sn < maxn
		//})

		if rec.QryAsInt("json", 0) == 1 {
			PrjHttpUtils.ResponseAsJSON(rec.RespW, json.AsJSONStringEx(false, false))
		} else {
			PrjHttpUtils.JSON2Table(rec.RespW, "", json.AsJSONString(false))
		}
	} else {
		var sb utils.BytesBuilder
		PrjHttpUtils.AppendIndexBody(&sb, "status", "status?type=99")
		PrjHttpUtils.AppendIndexBody(&sb, "msglist", "status?type=98&n=100&searchval=")
		//PrjHttpUtils.AppendIndexBody(&sb, "lst", "status?type=1&n=100&searchval=")
		PrjHttpUtils.ResponseBodyHtml(rec.RespW, sb.String())
	}
	return
}

func (this *PlgVxApi) LogInfoMessage(s string, args ...interface{}) {
	this.msglst.LogMsg(s, args...)
	utils.Log.Msgf(this.PlugId, utils.LogLV_INFO, 1, s, args...)
}

func (this *PlgVxApi) LogWarnMessage(s string, args ...interface{}) {
	this.msglst.LogMsg(s, args...)
	utils.Log.Msgf(this.PlugId, utils.LogLV_WARN, 1, s, args...)
}

func (this *PlgVxApi) OnObjectNotify(sender interface{}, notifytype int, data interface{}) (rval interface{}, err error) {
	if notifytype == utils.NOTIFY_TYPE_SETCONF {
		if conf, ok := data.(*wrapper.SuperValue); ok {
			err = this.ReloadConf(conf)
		} else {
			err = fmt.Errorf("非法的JSON配置")
		}
	} else if notifytype == utils.NOTIFY_TYPE_RELEASE {
		this.ReleaseFlag = 1
	}
	return
}

func CreateCloudVxApiPlugFunc(args ...interface{}) (rval interface{}, err error) {
	obj := &PlgVxApi{}
	if len(args) > 0 {
		if str, ok := args[0].(string); ok {
			obj.PlugId = str
		}
	}
	rval = obj
	return
}
